'''
Author: xiaonancheng
Date: 2023-07-04 14:30:18
https://www.cnblogs.com/xiaonancheng
Copyright (c) 2023 by @xiaonancheng, All Rights Reserved. 
'''
from django.shortcuts import render,redirect
from django.http import JsonResponse,HttpResponseRedirect


# Create your views here.

from BoosAPP.models import Boos,Food,F_type
from RMS.settings import BASE_DIR
from django.views.decorators.csrf import csrf_exempt

def login(request):# 登陆

    if request.method=="GET":
        return render(request,'boos/login.html',)
    elif request.method=="POST":
        username=request.POST.get('username')
        password=request.POST.get('password')
        if not username:
            # 不填用户名 直接提交 "" None
            return render(request,'boos/login.html',{'msg':'用户不能为空'})
        booss=Boos.objects.filter(name=username)
        if not booss:
            # 用户名 不存在
            return render(request,'boos/login.html',{'msg':'用户不存在'})
        boos=booss[0]
        if boos.password != password:
            # 密码错误
            return render(request,'boos/login.html',{'msg':'密码错误','username':username})
        # 一切通过 登陆成功 
        request.session['is_login']=True# 是否登陆
        request.session['bid']=boos.bid
        request.session['username']=boos.name
        request.session['u_type']='boos'


        return redirect('/')#到首页
    else:
        return JsonResponse({'msg':'非法请求'})
def register(request):#注册
    if request.method=="GET":
        return render(request,'boos/register.html')
    elif request.method=="POST":
        username=request.POST.get('username')
        pw1=request.POST.get('pw1')
        pw2=request.POST.get('pw2')
        if not username:
            # 不填用户名 直接提交 "" None
            return render(request,'boos/register.html',{'msg':'用户不能为空'})
        booss=Boos.objects.filter(username=username)
        if booss:
            return render(request,'boos/register.html',{'msg':'用户名已存在请重新输入'})
        if pw1!=pw2:
            return render(request,'boos/register.html',{'msg':'两次密码不一致'})
        boos=Boos(username=username,password=pw2)
        boos.save()
        return redirect('BoosAPP:login')
def logout(request):#登出

    """
    点击登出 返回 登陆页面 或者 首页 
    验证：是否在线 

    """
    if request.session['is_login']:
        # 方法一 清除 session
        request.session['is_login']=False
        request.session['bid']=''
        request.session['username']=''
        request.session['u_type']=''
        # 方法一 清除 session

        # 方法二 清除 session
        # request.session.clear()
        # 方法二 清除 session
    return redirect('/')

from django.core.paginator import Paginator #实现分页


def login_role_auth(fn):
    def wrapper(request,*args,**kwargs):
        if request.session.get('is_login', False) and request.session.get('u_type')=="boos" :
            return fn(request,*args,*kwargs)
        else:
            # 获取用户当前访问的url，并传递给/user/login/
            next = request.get_full_path() 
            request.session["is_login"]=False
            red = HttpResponseRedirect("/login/?"+next)
            return red
    return wrapper

@login_role_auth
def food_lis(request):#展示所有菜品
    page=int(request.GET.get('page',1))
    page_size=3
    foodlis=Food.objects.all()#[(page-1)*page_size:page*page_size]
    paginator = Paginator(foodlis, page_size)
    page_foods= paginator.get_page(page)
    return render(request,'boos/foodlist.html',locals())
def food_details(request):#菜品详情
    id =request.GET.get('id')
    food=Food.objects.get(pk=id)
    return render(request,'boos/food_details.html',{'food':food})

def edit_food(request):# 编辑菜品页面 
    page=int(request.GET.get('page',1))
    page_size=3
    foodlis=Food.objects.all()#[(page-1)*page_size:page*page_size]
    paginator = Paginator(foodlis, page_size)
    page_foods= paginator.get_page(page)
    f_types=F_type.objects.all()

    return render(request,'boos/edit_food.html',locals())
import time 

#@csrf_exempt #屏蔽csrf
def add_food(request):#增加菜品
    if request.method=="POST":
        name=request.POST.get('name')
        price=request.POST.get('price')
        info=request.POST.get('info')
        img_file=request.FILES.get('img_file')
        # f_t=img_file.name.split('.')[-1]
        f_name=str(int(time.time()*10000))+'.png'
        
        # img_file
        # img=request.POST.get('img')
        dir=BASE_DIR/'static/img/'
        with open(dir/f_name,'wb') as f:
            for line in img_file:
                f.write(line) 
        img='/static/img/'+f_name
        f_type=request.POST.get('f_type')
        f_t=F_type.objects.get(pk=f_type)
        food=Food(name=name,price=float(price),info=info,img=img,f_type=f_t)
        food.save()
        return redirect('BoosAPP:edit_food')

    
    return JsonResponse({'msg':'非法请求'})
def update_food(request):#修改菜品
    if request.method=="POST":
        fid=request.POST.get('fid')#修改的哪一个菜品
        if not fid:
            return JsonResponse({'msg':'缺少必要参数 菜品id'})
        food=Food.objects.filter(id=fid)
        if not food:
            return JsonResponse({'msg':'菜品id不存在'})
        food=food[0]

            


        name=request.POST.get('name')
        price=request.POST.get('price')
        info=request.POST.get('info')
        img_file=request.FILES.get('img_file')
        # f_t=img_file.name.split('.')[-1]
        f_name=str(int(time.time()*10000))+'.png'
        if img_file:

        # img_file
        # img=request.POST.get('img')
            dir=BASE_DIR/'static/img/'
            with open(dir/f_name,'wb') as f:
                for line in img_file:
                    f.write(line) 
            img='/static/img/'+f_name
            food.img=img
        f_type=request.POST.get('f_type')
        f_t=F_type.objects.get(pk=f_type)
        
        food.name=name
        food.price=float(price)
        food.info=info
        
        food.f_type=f_t
        food.save()
        print(request.path)
        return redirect('BoosAPP:edit_food')

    
    return JsonResponse({'msg':'非法请求'})
   
def delete_food(request):#删除菜品
    fid=request.GET.get('fid')
    food=Food.objects.get(pk=fid)
    food.delete()
    return redirect('BoosAPP:edit_food')

